package com.dexafree.materialList.listeners;

import com.dexafree.materialList.card.Card;
import com.dexafree.materialList.card.CardLayout;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.app.Context;
import ohos.multimodalinput.event.TouchEvent;

/**
 * RecyclerItemClickListener
 *
 * @author hw
 * @since 2021/5/26
 */
public class RecyclerItemClickListener implements ListContainer.ItemClickedListener {
    private ListContainer mRecyclerView;

    public interface OnItemClickListener {
        void onItemClick(final Card card, int position);

        void onItemLongClick(final Card card, int position);
    }

    private OnItemClickListener mListener;

    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(TouchEvent event) {
                return true;
            }

            @Override
            public void onLongPress(TouchEvent event) {
                CardLayout childView = (CardLayout) findChildViewUnder(mRecyclerView,
                        event.getPointerScreenPosition(0).getX(),
                        event.getPointerScreenPosition(0).getY());
                if (childView != null && mListener != null) {
                    mListener.onItemLongClick(childView.getCard(), mRecyclerView.getIndexForComponent(childView));
                }
            }
        });
    }

    @Override
    public void onItemClicked(ListContainer listContainer, Component component, int position, long l) {
        CardLayout childView = (CardLayout) component;
        mListener.onItemClick(childView.getCard(), position);
    }

    public void setRecyclerView(ListContainer recyclerView) {
        mRecyclerView = recyclerView;
    }

    public Component findChildViewUnder(ListContainer listContainer, float x, float y) {
        int count = listContainer.getChildCount();
        for (int i = count - 1; i >= 0; --i) {
            Component child = listContainer.getComponentAt(i);
            float translationX = child.getTranslationX();
            float translationY = child.getTranslationY();
            if (x >= (double) child.getLeft() + translationX && x <= (double) child.getRight()
                    + translationX && y >= (double) child.getTop() +
                    translationY && y <= (double) child.getBottom() + translationY) {
                return child;
            }
        }
        return null;
    }
}